/*
* PM util jscript
* create by Lven Yang.20100520
*/
String.format = function(str) {
    var args = arguments, re = new RegExp("%([1-" + args.length + "])", "g");
    return String(str).replace(
    re,
    function($1, $2) {
        return args[$2];
    }
    );
};

var  Util = {};
/*
* 基本配置
*/
Util.Config = {
    TextBoxDefaultColor: "#999",//文本框默认字体颜色
    TextBoxActiveColor:"#000",//文本框激活字体颜色
	JsContextPath:'js/pm/',//JS path,
	JsPtContextPath:'js/',//JS path
	PopOkBtn:'确定',//弹出框确定按钮
	PopCacelBtn:'取消',//弹出框取消按钮
	ToolBarBtnPath:'images/pm/corp/v1/themes/default/images/icon/',
	PageLoadingPath:'images/pm/corp/v1/themes/default/images/page/page_loading.gif',
	EmptyImgPath:'images/pm/statics/e.gif',
	errorIcoPath:'images/pm/corp/v1/themes/default/images/form/error.gif',
	rightIcoPath:'images/pm/corp/v1/themes/default/images/form/right.gif'
}
/*
* 加载Javascript
*/
Util.loadScript = function(url){
	document.write('<script type="text/javascript" src="' + Util.Config.JsContextPath + url + '"><\/script>');
}
Util.loadJsScript = function(url){
	document.write('<script type="text/javascript" src="' + Util.Config.JsPtContextPath + url + '"><\/script>');
}
/*
* 检测用户是否开启了浏览器的Cookie功能
*/
Util.USERCONFIG = function(){
	if(!navigator.cookieEnabled){jAlert("您的浏览器不支持Cookie或Cookie功能被禁用,为了您更好的体验,您需要开启浏览器的Cookie功能","温馨提示");return;};   
    document.cookie = "testcookie=yes;";   
    var cookieSet = document.cookie;   
    if (cookieSet.indexOf("testcookie=yes") == -1){
		jAlert("您的浏览器不支持Cookie或Cookie功能被禁用,为了您更好的体验,您需要开启浏览器的Cookie功能","温馨提示");return;
	}
}
/*
* Html特殊字符转换
*/
Util.htmlDecode = function(val){
	return val&&$.trim(val.replace(/\r/g, '').replace(/<br>/ig,'\n').replace(/<br \/>/ig,'\n').replace(/&nbsp;/g, ' ').replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g, '&'))||'';
}
Util.htmlEncode = function(val){
	return val&&$.trim(val.replace(/\r/g, '').replace(/\n/g,'<br />').replace(/&/g, '&amp;').replace(/ /g, '&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\x01/g, '<font color=red>').replace(/\x02/g, '</font>'))||'';
}
Util.formEncode = function(val){
    return val&&val.replace(/\"/g, '&#34;').replace(/\'/g, '&#39;')||'';
}
/**
* 验证; e.g:Util.Validate.Check('mobile',value);
*/
Util.Validate = {
	_reg:{
		intege:"^-?[1-9]\\d*$",					//整数
		intege1:"^[1-9]\\d*$",					//正整数
		intege2:"^-[1-9]\\d*$",					//负整数
		num:"^([+-]?)\\d*\\.?\\d+$",			//数字
		num1:"^[1-9]\\d*|0$",					//正数（正整数 + 0）
		num2:"^-[1-9]\\d*|0$",					//负数（负整数 + 0）
		decmal:"^([+-]?)\\d*\\.\\d+$",			//浮点数
		decmal1:"^[0-9]*.\\d*$",　　	//正浮点数
		decmal2:"^-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*)$",　 //负浮点数
		decmal3:"^-?([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0)$",　 //浮点数
		decmal4:"^[1-9]\\d*.\\d*|0.\\d*[1-9]\\d*|0?.0+|0$",　　 //非负浮点数（正浮点数 + 0）
		decmal5:"^(-([1-9]\\d*.\\d*|0.\\d*[1-9]\\d*))|0?.0+|0$",　　//非正浮点数（负浮点数 + 0）
		email:/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, //邮件
		color:"^[a-fA-F0-9]{6}$",				//颜色
		url:"^http[s]?:\\/\\/([\\w-]+\\.)+[\\w-]+([\\w-./?%&=]*)?$",	//url
		chinese:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2D]+$",					//仅中文
		ascii:"^[\\x00-\\xFF]+$",				//仅ACSII字符
		zipcode:"^\\d{6}$",						//邮编
		mobile:/^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|14[7|5]|18[0|5|6|7|8|9])\d{8}$/,				//手机
		ip4:"^(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)\\.(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)$",	//ip地址
		notempty:"^.+$",						//非空
		picture:"(.*)\\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga)$",	//图片
		rar:"(.*)\\.(rar|zip|7zip|tgz)$",								//压缩文件
		date:"^\\d{4}(\\-|\\/|\.)\\d{1,2}\\1\\d{1,2}$",					//日期
		qq:"^[1-9]*[1-9][0-9]*$",				//QQ号码
		//tel:"^(([0\\+]\\d{2,3}(-)?)?(0\\d{2,3})(-)?)?(\\d{7,8})(-(\\d{3,}))?$",	//电话号码的函数(包括验证国内区号,国际区号,分机号)
		tel:"^(0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?$",    //区号+座机号码
		name:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z][\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z\\s.]{1,}$", //真实姓名由汉字、英文字母、空格和点组成，不能以空格开头至少两个字
		addressname:"^[\\u4E00-\\u9FA5\\uF900-\\uFA2Da-zA-Z]{1,}$",	//收货人
		username:"^[0-9a-zA-Z_\u0391-\uFFE5]{3,15}$",					//用来用户注册。匹配由数字、26个英文字母或者下划线组成的字符串 3-15个字符串之间 
		letter:"^[A-Za-z]+$",					//字母
		letter_u:"^[A-Z]+$",					//大写字母
		letter_l:"^[a-z]+$",					//小写字母
		idcard:"^[1-9]([0-9]{14}|[0-9]{16}[0-9xX])$",	//身份证
		documentscard:"^[A-Za-z0-9]+$",			//只能为数字（0-9）和字母(A-Z/a-z)
        passwrd:"^[\\w-@#$%^&*]{6,20}$",			//密码保证6-20位的英文字母/数字/下划线/减号和@#$%^&*这些符号
		specialstr:"^(a-z|A-Z|0-9)*[^~!#$%^&*()']*$"	//只可输入英文、数字、和中文
	},
	Check: function(type,value){
		if(Util.Validate._reg[type] == undefined){
			alert("Type " + type + " is not in the data");
			return false;
		}
		var reg;
		if(typeof Util.Validate._reg[type] == "string"){
			reg = new RegExp(Util.Validate._reg[type]);
		}
		else{
			reg = Util.Validate._reg[type];
		}
		return reg.test(value);
	},
	BindForm: function(ele,handler){
		var form = $(ele);
		form.submit(function(){
			if($(this).attr("notvali") == "1"){
				return true;
			}
			var state = true;
			var errorArr = {};
			var checkArr = form.find("[vali]");
			var allArr = {};
			for(var i = 0,len = checkArr.length; i < len; i++){
				var typeArr = $(checkArr[i]).attr("vali").split("|");
				for(var j = 0,jlen = typeArr.length; j < jlen; j++){
					allArr[i.toString()] = checkArr[i];
					if(!(Util.Validate.Check(typeArr[j],checkArr[i].value) ||  ($(checkArr[i]).attr("require") == "0" && $.trim(checkArr[i].value) == ""))){
						state = false;
						if(!errorArr[i.toString()]){
							errorArr[i.toString()] = checkArr[i];
						}
						break;
					}
					if(typeArr[j] == "notempty"){
						var min = $(checkArr[i]).attr("min") ? Number($(checkArr[i]).attr("min")) : 0;
						var max = $(checkArr[i]).attr("max") ? Number($(checkArr[i]).attr("max")) : -1;
						var count = $.trim(checkArr[i].value).length;
						if(!(min <= count && (max == -1 || max >= count))){
							state = false;
							if(!errorArr[i.toString()]){
								errorArr[i.toString()] = checkArr[i];
							}
						}
					}
				}
			}
			if(handler && handler.DefaultCallBack){
				handler.DefaultCallBack(allArr);
			}
			if(handler && handler.ErrorCallBack){
				handler.ErrorCallBack(errorArr);
			}	
			if(handler && handler.ReturnCallBack){
				return handler.ReturnCallBack($(this),state);
			}
			else{
				return state;
			}
		});
	},
	InputBlurCheck:function(ele){
		var input = $(ele),
			state = true,
			typeArr = input.attr("vali").split("|");
		
		for(var j = 0,jlen = typeArr.length; j < jlen; j++){
			if(!(Util.Validate.Check(typeArr[j],input.val()) ||  (input.attr("require") == "0" && $.trim(input.val()) == ""))){
				state = false;
				break;
			}
			if(typeArr[j] == "notempty"){
				var min = input.attr("min") ? Number(input.attr("min")) : 0;
				var max = input.attr("max") ? Number(input.attr("max")) : -1;
				var count = $.trim(checkArr[i].val()).length;
				if(!(min <= count && (max == -1 || max >= count))){
					state = false;
				}
			}
		}
		return state;
	}//End Util.Validate.InputBlurCheck
	
}//End Util.Validate

/*
* 文本框操作
*/
Util.TextBox={
	 BindDefaultText: function(ele,text){//Bind defalut text box.
		if(ele.value == ""){
			ele.style.color = Util.Config.TextBoxDefaultColor;
       	 	ele.value = text;
		}
		else if(ele.value == text){
			ele.style.color = Util.Config.TextBoxDefaultColor;
		}
        ele.onblur = function(){
            if(ele.value == ""){
                ele.value = text;
                ele.style.color = Util.Config.TextBoxDefaultColor;
            }
            else{
                ele.style.color = Util.Config.TextBoxActiveColor;
            }
        };
        ele.onfocus = function(){
            ele.style.color = Util.Config.TextBoxActiveColor;
            if(ele.value == text){
                ele.value = "";
            }
        };
        ele.GetValue = function(){
            if(ele.value == text){
                return "";
            }
            return ele.value;
        };
		ele.Clear = function(){
			ele.value = "";
			ele.onblur();
		};
        return ele;
    },
	onlyNums:function(e){//Limit text box only type number.
		var key=window.event?e.keyCode:e.which;if(key==8||key==0)
		{return true;}
		var keychar=String.fromCharCode(key);reg=/\d/;return reg.test(keychar);	
	}
};
/*
* 提交数据提示
*/
Util.MsgBox={
	show:function(message,top,time){//传入参数：显示信息、离顶部距离、显示时间
		$("#show_state").remove();
	    var e=$(document),
		    c=$('<div class="wn_msg" id="show_state" name="show_state">'+message+'</div>');
		$("body").append(c);
		$("#show_state").css({top:top,left:(e.width()-c.width())/2});
		setTimeout('Util.MsgBox.close_msg()',time*1000);
	},
	close_msg:function(){
		$("#show_state").hide();
	},
	//Ajax Submit show loading...
	page_loading:function(showArr){
		if($("#loading_outer").length==0){
			$("body").append($("<div>").attr("id","loading_outer").css({
				width:"950px",
				height:"300px",
				position:"absolute",
				"z-index":999,
				background:"url("+Util.Config.EmptyImgPath+") repeat",
				display:"none"
			}).html("<span style=\"background:#FFFAEA url("+Util.Config.PageLoadingPath+") no-repeat 8px center; " +
					"padding:4px 28px; border:1px solid #FFE591; position:absolute; left:620px; top:14px\" id=\"loading_span\">"+showArr.msg+"</span>"));
		}
		//判断是否显示Loading图标,如1-Right,0-Error
		if(showArr.returnVal!="undefined")
		{
			var loadouter = $("#loading_span");
			switch(showArr.returnVal){
				case 0:
					loadouter.css({background:"url("+Util.Config.errorIcoPath+") #FFFAEA no-repeat 8px center"}).html(showArr.msg);
				break;
				case 1:
					loadouter.css({background:"url("+Util.Config.rightIcoPath+") #FFFAEA no-repeat 8px center"}).html(showArr.msg);
				break;
				case 2:
					loadouter.css({background:"url("+Util.Config.PageLoadingPath+") #FFFAEA no-repeat 8px center"}).html(showArr.msg);
				break;
			}
		}

		var loadingouter = $("#loading_outer");
		
		var ptop =  showArr.top;
		var pleft = showArr.left;
		loadingouter.css({
			top:ptop+"px",
			left:pleft+"px"
		}).show();
		//设置隔几秒隐藏DIV
		if(showArr.timeOut){
			setTimeout(function(){$("#loading_outer").hide()},showArr.timeOut*1000);
		}
		//让Div隐藏掉
		if(showArr.hide){
			$("#loading_outer").hide();
		}
	}

};
/*
* 文本域字数限制插件.
* -By Lven Yang.
*/
(function ($) {

$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
    	var parts = el.value;
    	if ( settings.words )
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	$charsLeft = $form.find(settings.feedback);

		var _top  = $(this).offset().top,
			 _width = $(this).outerWidth();
			 _height = $(this).height();
			 _left = $(this).offset().left;
		$charsLeft.css({
			top:_top + (_height/2) + 15 + "px",
			left:_left + "px"
		})

    	function limitCheck(event) {
        	var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;
        	if ( !exceeded )
        		return;

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37: 
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }
		//TextArea focus show tip
		function textAreaFocus(){
			$charsLeft.fadeIn('fast')	
		}
		//TextArea blur hide tip
		function textAreaBlur(){
			$charsLeft.fadeOut('fast')	
		}

        var updateCount = function () {
            var len = length(field),
            	diff = limit - len;

            $charsLeft.html( (len || "0") + '/' +  limit);

            // truncation code
            if (settings.hardLimit && diff < 0) {
            	field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit*2)-1).join('') :
            		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }
		$field.focus(textAreaFocus); //show
		$field.blur(textAreaBlur);   //hide

        updateCount();
    });
};

$.fn.maxlength.defaults = {
    useInput : false,
    hardLimit : true,
    feedback : '.charsLeft',
    words : false
};

})(jQuery);
/*
* bgiframe Div 遮住SelectBox
*/
(function($){
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);
/*
* 初始化Form表单
*/
Util.Form={
	initInput:function()
	{
		var jParent = $(document);
		//设置文本框获取焦点及失去焦点样式
		$("input[type=text], input[type=password], textarea",jParent).addClass("textInput").focus(
			function(e){$(this).addClass('focus')
		}).blur(
			function(e){$(this).removeClass('focus')
		});
		//设置文本框如果是 只读/禁用 时的样式
		$("input[readonly], textarea[readonly]", jParent).addClass("readonly");
		$("input[disabled=true], textarea[disabled=true]", jParent).addClass("disabled");
	},
	initToolBarBtn:function()
	{
		//设置工具栏的ICON图标.
		$('#top_bar a img').each(function(){
			$(this).attr('src',Util.Config.ToolBarBtnPath + $(this).attr('id') + '.gif');								   
		});
	},
	initMoreToolBarBtn:function()
	{
		//设置工具栏的ICON图标.
		$('.top_bar a img').each(function(){
			$(this).attr('src',Util.Config.ToolBarBtnPath + $(this).attr('id') + '.gif');								   
		});
	},
	textAreaLimit:function(obj)
	{
		 $('textarea[limt=limited]').maxlength({
            'feedback' : obj
        });
	},
	inputDisabled:function(isDisd)
	{
		var formEle = $("input[type=text],input[type=checkbox],input[type=radio],input[type=file],textarea,select","form[vali='3']");
		if(isDisd)
		{	formEle.attr("disabled","true").addClass("disabled");
			$("input[type=text]:first").focus();
		}
		else
		{
		    formEle.removeAttr("disabled").removeClass("disabled");
			$("input[type=text]:first").focus();
		}
	},
	cleanInputVal:function()
	{
		var formEle = $("input[type=text],input[type=file],textarea","form[vali='3']");
		formEle.val("");
	},
	initDocTitle:function()
	{
		var pTitle  = parent.document.title,
		    cTtitle = document.title;
		if(pTitle.indexOf(cTtitle) < 0)
			parent.document.title = document.title + ' - ' + parent.document.title;
	},
	hasClassName:function(className){
		return (new RegExp(("(^|\\s)" + className + "(\\s|$)"), "i").test(className));
	},
	hasClassName:function(className,ele){
		return (new RegExp(("(^|\\s)" + className + "(\\s|$)"), "i").test(ele.className));
	},
	addClassName:function(className,ele){
	  var currentClass = ele.className;
	  currentClass = currentClass?currentClass:"";
	  if(!new RegExp(("(^|\\s)" + className + "(\\s|$)"), "i").test(currentClass)){
			ele.className = currentClass + ((currentClass.length > 0)? " " : "") + className;
	  }
	  return ele.className;
	},
	toolBarBtnDisabled:function(btnAttr)
	{
		if(btnAttr != "undefined")
		{
			for(var i=0;i<btnAttr.length;i++)
			{
				var ele = document.getElementById(btnAttr[i]);
				if(Util.Form.hasClassName("zPushBtn",ele)){
					Util.Form.addClassName("zPushBtnDisabled",ele);
					if(ele.onclick){
					   ele.onclickbak = ele.onclick;
					}
					ele.onclick = null;
				 }
			}
		}
	},
	toolBarBtnEnabled:function(btnAttr)
	{
		if(btnAttr != "undefined")
		{
			for(var i=0;i<btnAttr.length;i++)
			{
				var ele = document.getElementById(btnAttr[i]);
				if(Util.Form.hasClassName("zPushBtnDisabled",ele)){
					ele.className="zPushBtn";
					if(ele.onclickbak){
						ele.onclick = ele.onclickbak;
					}
				}
			}
		}
	},
	fillSelOptions:function(opt)
	{
		//param:ele,data,defaultKey,defOpt,changeEvt
		//清除selectBox选项
		var select_obj = opt.ele;
		select_obj[0].options.length = 0;
		if(opt.defOpt)
	    	select_obj[0].options.add(new Option(opt.defOpt[0],opt.defOpt[1]));
		
		for (var o in opt.data) {
			var option_value = opt.changeEvt ? opt.data[o]["selVal"] : o;
			var option_text = opt.changeEvt ? opt.data[o]["selTxt"] : opt.data[o];
			//var new_option = new Option(option_text,option_value);
			var new_option = opt.changeEvt ? $('<option value="'+option_value+'" id="'+opt.data[o]["selChgID"]+'">'+option_text+'</option>') : $('<option value="'+option_value+'">'+option_text+'</option>');

			select_obj.append(new_option);
	
			if(opt.defaultKey != null && opt.defaultKey == option_value) 
			  select_obj[0].options[select_obj[0].options.length - 1].selected = true;
		}

	},
	isNull:function(inVal,returnVal)
	{
		if(inVal == null || inVal == 'undefined')
		{
			return returnVal;
		}
		else{
			return inVal;	
		}
	},
	initValiLayout:function()
	{
		Util.Form.initInput();                   	//init form input
		Util.Form.initToolBarBtn();					//init tool bar btn icon
//		Util.Form.initDocTitle();        			//init parent document title
		Util.Form.textAreaLimit('#textAreaTip');	//init textArea limit
		Util.Form.inputDisabled(true);			//init input disabled
		Util.ValiForm.Bind($("form[vali='3']"));    //bind form validate
	}
};
/*
* 表单ToolTip验证
*/
Util.ValiForm = (function(){
	var _ClassType = {remain:"re_remain",error:"re_error",suc:"re_correct"};
	var _MsgTemp = '<a class="re_error"></a>';
	var _valiArr = [];
	var _specialArr = {};
	var _form;
	var TipxOffset = 35;
	var TipyOffset = 190;
	
	//AJAX取结果
	var ajaxInput = function(ele){
		var url = ele.attr("url") + encodeURIComponent($.trim(ele.val()));
		//ele.removeAttr("valistate");
		$.ajax({
			url:url,
			type:"GET",
			success:function(r){
				if(r == "ok"){
					showSucTips(ele);
					ele.attr("valistate","1");
				}
				else{
					showErrorTips(ele,r);
					ele.attr("valistate","0");
				}
			}
		})
	}

	//显示通过信息
	var showSucTips = function(ele){
		ele.parent().find(".re_error").remove();
		ele.removeClass('error');
		$("#tooltip").remove();
	}
	
	//显示错误信息
	var showErrorTips = function(ele,msg){
		//--以下注释部分是方法来的主体
//		re_errorDom = $(ele.parent()).find(".re_error");
//		if(!re_errorDom.length){
//			errorDom = $(String.format(_MsgTemp));
//			ele.addClass('error');
//			ele.parent().append(errorDom);
//			showErrToolTip(ele,msg); //Show Tool Tip
//		}
//		else
//		{
//			re_errorDom.remove();
//			errorDom = $(String.format(_MsgTemp));
//			ele.addClass('error');
//			ele.parent().append(errorDom);
//			showErrToolTip(ele,msg);  //Show Tool Tip
//		}
		
		//--以下部分是2011-01-19Jason修改的部分
		re_errorDom = $(ele.parent()).find(".re_error");
		if(re_errorDom.length){
			re_errorDom.remove();
		}
		errorDom = $(String.format(_MsgTemp));
		ele.addClass('error');
		if(typeof(msg) != 'undefined'){
			test='<a class="re_error">'+msg+'</a>'; 
			ele.parent().append(test);
//			showErrToolTip(ele,msg);  //Show Tool Tip
		}
	}
	
	var showErrToolTip = function(ele,msg){
		//var tipEle = ele.next("a");
		var tipEle = ele.parent().find(".re_error");
		tipEle.hover(function(e){
			var c=$('<span id="tooltip">'+msg+'</span>');
			$("#comm_form").append(c);
			$("#tooltip")
				.css("top",$(this).offset().top - TipxOffset)
				.css("left",$(this).offset().left - TipyOffset)
				.show()
				.bgIframe();		
		},
		function(){	
			$("#tooltip").remove();
		});	
		//tipEle.mousemove(function(e){
//			$("#tooltip")
//				.css("top",(e.pageY - 22) + "px")
//				.css("left",(e.pageX-180) + "px");
//		});					
	}
	
	//是否必须要验证
	var rateFun = function(ele){
		//是否需要必须验证
		var state = true;
		
		if((ele.attr("rate") == "0" && $.trim(ele.val()) == ""))
		{
			showSucTips(ele);
			state = true;
		}
		else
		{
			if(checkFun(ele))
			{
				showSucTips(ele);
			}
			else
			{
				showErrorTips(ele,ele.attr("errormsg"));	
				state = false;
			}
		}
		return state;
	}
	
	//验证函数
	var checkFun = function(ele){
		var state = true;
		var typeArr = ele.attr("vali").split("|");
		for(var i = 0,len = typeArr.length; i < len; i++){
			if(!Util.Validate.Check(typeArr[i],ele.val()) || ($.trim(ele.val()) == "")){
				state = false;
				break;
			}
		}
		return state;
	}
	
	var ajaxoldvalue;
	var bindEvents = function(){
		for(var i = 0,len = _valiArr.length; i < len; i++){
			if(_specialArr[i]){
				//绑定特别的验证
				var obj = _specialArr[i];
				obj.ele.bind("focus",obj,function(e){
					ajaxoldvalue = $(this).val();
				}).bind("blur",obj,function(e){
					var ele = $(this);
					switch(e.data.type){
						case "ajax":
							if(checkFun(ele)){
								if(ajaxoldvalue != $(this).val()){
									ajaxInput(ele);
								}
							}
							else{
								showErrorTips(ele,ele.attr("errormsg"));
							}
							break;
						case "rate":
							rateFun(ele);
							break;
					}
				}).bind("keyup",obj,function(e){
					var ele = $(this);
					switch(e.data.type){
						case "ajax":
							if(checkFun(ele)){
								if(ajaxoldvalue != $(this).val()){
									ajaxInput(ele);
									ajaxoldvalue = $(this).val();
								}
							}
							else{
								showErrorTips(ele,ele.attr("errormsg"));
							}
							break;
						case "rate":
							rateFun(ele);
							break;
					}	
				})
			}
			else{
				//绑定普通的验证
				var item = _valiArr[i];
				item.bind("blur",function(){
					var ele = $(this);
					if(checkFun(ele)){
						showSucTips(ele);
					}
					else{
						showErrorTips(ele,ele.attr("errormsg"));
					}
				})
				.bind("keyup",function(){
					var ele = $(this);
					if(checkFun(ele)){
						showSucTips(ele);
					}
					else{
						showErrorTips(ele,ele.attr("errormsg"));
					}
				})
			}
		}
		
		//_form.submit(function(e){
//			var state = true;
//			for(var i = 0,len = _valiArr.length; i < len; i++){
//				var ele = _valiArr[i];
//				if(_specialArr[i] && _specialArr[i].type=='rate'){
//					if(!rateFun(ele)){
//						state = false;
//					}
//				}
//				else{
//					if(!checkFun(ele)){
//						showErrorTips(ele,ele.attr("errormsg"));
//						state = false;
//					}
//				}
//			}
//			if(state){
//				for(var k in _specialArr){
//					var item = _specialArr[k];
//					if(item.type == "ajax" && item.ele.attr("valistate") == "0"){
//						state = false;
//						item.ele[0].select();
//						return state;
//					}
//				}
//			}
//			return state;
//		});
	}
	
	var Return = {
		Bind: function(form){
			_form = form;
			_valiArr.length = 0;
			_form.find("[vali]").each(function(i){
				var ele = $(this);
				_valiArr.push(ele);
				if(ele.attr("url")){
					_specialArr[i] = {ele:ele,type:"ajax"};
				}
				else if(ele.attr("rate")){
					_specialArr[i] = {ele:ele,type:"rate"};
				}
			});
			bindEvents();
		},
		formValiState: function()
		{
			var state = true;
			for(var i = 0,len = _valiArr.length; i < len; i++){
				var ele = _valiArr[i];
				if(_specialArr[i] && _specialArr[i].type=='rate'){
					if(!rateFun(ele)){
						state = false;
					}
				}
				else{
					if(!checkFun(ele)){
						showErrorTips(ele,ele.attr("errormsg"));
						state = false;
					}
				}
			}
			if(state){
				for(var k in _specialArr){
					var item = _specialArr[k];
					if(item.type == "ajax" && item.ele.attr("valistate") == "0"){
						state = false;
						item.ele[0].select();
						return state;
					}
				}
			}
			
			return state;	
		},
		formValiClean: function()
		{
			//Clean form vali css
			_form.find("[vali]").each(function(i){
				var ele = $(this);
				ele.parent().find(".re_error").remove();ele.removeClass("error");$("#tooltip").remove();// remove vali
			});	
		},
		isBindFormVali: function()
		{
			var _valiEvtArr = [];
			$("form[vali='3']").find("[vali]").each(function(i){
				var ele = $(this);
				if(ele.data("events")){ 
					_valiEvtArr.push(ele);
				}
			 });
			return _valiEvtArr.length;
		}
	};
	
	return Return;
})();

/*
* 弹出框
*/
//load drag script plugins
Util.loadScript('drag.plugins.js');
(function($) {
	
	$.alerts = {
		verticalOffset: -150,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: Util.Config.PopOkBtn,         // text for the OK button
		cancelButton: Util.Config.PopCacelBtn, // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs
		
		// Public methods
		
		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', null , function(result) {
				if( callback ) callback(result);
			});
		},
		
		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', null , function(result) {
				if( callback ) callback(result);
			});
		},
			
		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', null , function(result) {
				if( callback ) callback(result);
			});
		},
		
		iframe: function(message, title, option, callback) {
			if( title == null ) title = 'iframe';
			$.alerts._show(title, message, null, 'iframe', option , function(result) {
				if( callback ) callback(result);
			});
		},
		
		// Private methods
		
		_show: function(title, msg, value, type, option, callback) {
			
			$.alerts._hide();
			$.alerts._overlay('show');
			
			$("BODY").append(
			  '<div class="popup_container" id="popup_contain">'+
  			  '<div id="popup_msg_box_wrap" class="popup_main">'+
              '<div style="cursor: move;" id="popup_msg_title" class="popup_title">'+
              '<h3></h3><button title="关闭" href="javascript:void(0)" id="mess_float_box_close"></button>'+
              '</div><div class="popup_container_tips" id="popup_messages">'+
              '<div class="gb_tips"><p id="popup_msg"></p><div class="prompt_err"></div>'+
	          '</div></div> <div class="global_tip_button" id="mess_float_box_button">'+
              //'<button id="mess_float_box_submit" type="submit" class="bt_tx2">确认</button>'+
              '</div></div></div>'
			  );
			
			if( $.alerts.dialogClass ) $("#popup_contain").addClass($.alerts.dialogClass);
			
			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
			//width set
			if(option)$("#popup_msg_box_wrap").css({width: option.width});
			
			$("#popup_contain").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			}).bgiframe();
			
			$("#popup_msg_title h3").text(title);
			$(".gb_tips").addClass(type);
			$("#popup_msg").text(msg);
			$("#popup_msg").html( $("#popup_msg").text().replace(/\n/g, '<br />') );

			$(".popup_container").css({
				width: $("#popup_msg_box_wrap").outerWidth()
			});
			
			$.alerts._reposition();
			$.alerts._maintainPosition(true);
			
			switch( type ) {
				case 'alert':
					$("#mess_float_box_button").html('<button class="bt_tx3" id="popup_ok">' + $.alerts.okButton + '</button>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#mess_float_box_button").html('<button class="bt_tx3" id="popup_ok">' + $.alerts.okButton + '</button> <button class="bt_tx3" id="popup_cancel">' + $.alerts.cancelButton + '</button>');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$('#popup_msg').after('<input type="text" class="prompt_txt" id="popup_prompt" />');
					$("#mess_float_box_button").html('<button class="bt_tx3" id="popup_ok">' + $.alerts.okButton + '</button> <button class="bt_tx3" id="popup_cancel">' + $.alerts.cancelButton + '</button>');
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						if(val==''){$('.prompt_err').text(value).show();return false;}
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					$("#popup_prompt").focus().select();
				break;
				case 'iframe':
					$('#popup_messages').hide();
					$('#popup_msg_title').after('<iframe id="'+option.ID+'" name="'+option.ID+'" frameborder="0" width="100%" height="'+option.height+'" src="'+option.src+'"></iframe>');
					if(option.box_btn)
					{
						if( option.okBtn ) $.alerts.okButton = option.okBtn;
						$("#mess_float_box_button").html('<button class="bt_tx3" id="popup_ok">' + $.alerts.okButton + '</button> <button class="bt_tx3" id="popup_cancel">' + $.alerts.cancelButton + '</button>');
					}
					$("#popup_ok").click( function() {
						 if( option.callback ) option.callback(option.callbackParam);
						 //document.getElementById(option.ID).contentWindow.option.callback(); 
						//$.alerts._hide();
						//if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						//if( callback ) callback(false);
					});
					//Close window callback
					$("#mess_float_box_close").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});

				break;
			}

			$("#mess_float_box_close").click( function() {
				$.alerts._hide();
				$.alerts.dialogClass = null;
			});
			
			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_contain").draggable({ handle: $("#popup_msg_title") });
					$("#popup_msg_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},
		
		_hide: function() {
			$("#popup_contain").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},
		
		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('<div id="popup_overlay"></div>');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},
		
		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_contain").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_contain").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;
			
			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
			
			$("#popup_contain").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},
		
		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}
	}
	//Close pop-up window
	jClose = function(){
		$.alerts._hide();
	}
	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};	
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	jIframe = function(message, title, option, callback) {
		$.alerts.iframe(message, title, option, callback);
	}
	
})(jQuery);

/*
* 表单验证
*/
jQuery(function($){ 
	$("form[vali='1']").each(function(){
		$(this).find("[valitype='ajax']").bind("blur",function(){
			if($(this).attr("url") != undefined){
				Member.FormAjaxMethod($(this));
			}
		});
		Util.Validate.BindForm(this,
						  {
							  DefaultCallBack: function(arr){
								  for(var i in arr){
									  var dom = $(arr[i]);
									  var errorDom = dom.parent().find(".errorSpan").not("[rel='ajax']");
									  if(errorDom.length){
										  $(errorDom).hide();
										  errorDom.parent().find(".t-normal").show();
									  }
								  }
							  },
							  ErrorCallBack:function(errorArr){
								  for(var i in errorArr){
									  var dom = $(errorArr[i]);
									  var errorDom = $(dom.parent()).find(".errorSpan").not("[rel='ajax']");
									  $(dom.parent()).find(".errorSpan").hide();
									  if(!errorDom.length){
										  errorDom = $('<span class="errorSpan">'+dom.attr("errormsg")+'</span>');
										  dom.parent().append(errorDom);
									  }
									  if(dom.attr("valistate") != "0"){
										  errorDom.parent().find(".t-normal").hide();
										  errorDom.show();
									  }
									  dom.bind("keyup",function (){
										  if(Util.Validate.InputBlurCheck($(this))){
											  $(this).parent().find(".errorSpan").hide();
										  }else{
											  $(this).parent().find(".errorSpan").show();	
										  }
									  });
								  }
							  
							  },
							  ReturnCallBack: function(form,r){
								  var ajaxList = form.find("[url]");
								  for(var i = 0,len = ajaxList.length; i < len; i++){
									  if($(ajaxList[i]).attr("valistate") == "0"){
										  ajaxList[i].select();
										  return false;
									  }
								  }
								  
								  var rateList = form.find("[rate]");
								  for(var i = 0,len = rateList.length; i < len; i++){
									  var item = $(rateList[i]);
									  var pNode = document.getElementById(item.attr("rate"));
									  if(pNode){
										  if($(pNode).val() != item.val()){
											  var errorDom = $(item.parent()).find(".errorSpan").not("[rel='ajax']");
											  if(!errorDom.length){
												  errorDom = $('<span class="errorSpan">'+item.attr("errormsg")+'</span>');
												  item.parent().append(errorDom);
											  }
											  return false;
										  }
									  }
								  }
								  
								  if(form.attr("onreturn")){
									  var rState = eval(form.attr("onreturn"));
									  if(!rState){
										  return false;
									  }
								  }
								  return r;
							  }
						  });
	})
});//End form validate.

//DataGrid
Grid = function(config) {
  this.titleTable = $('#'+config.titleTable);
  this.dataTable = $('#'+config.dataTable);
  this.widths = config.widths;
  this.height = config.height;
  this.init();
}

Grid.prototype = {
  
  init : function() {
    var entity = this;
    
    this.titleTable.wrap('<div class="tableColumn"></div>');
    this.titleDiv = this.titleTable.parent();
    
    this.dataTable.wrap('<div class="tableContent"></div>');
    this.dataDiv = this.dataTable.parent();
    
		this.updateHeight();
		
    this.updateWidth();
      
  },
  updateAll : function() {
		this.updateHeight();
    	this.updateWidth();
  },
  updateWidth : function() {
    var entity = this;
    
    //更新第一列的宽度
    var dataTableTdsFirst = this.dataTable.find('tr.row:first td');
    dataTableTdsFirst.each(function(i){
      if(entity.widths[i])
        $(this).width(entity.widths[i]);
    });

    //隔行变色
//	var dataTableTrs = this.dataTable.find('tr.row');
//	dataTableTrs.each(function(i){
//	  if((i+1)%2==0)
//		$(this).addClass('high');
//	});
		
    //设置表头宽度
    var titleTableTds = this.titleTable.find('tr td');
    titleTableTds.each(function(i){
      $(this).width(entity.widths[i]);
    });
		
    //更新表格宽度(判断是否需要显示滚动条)
    if(this.dataDiv.get(0).clientHeight < this.dataDiv.get(0).scrollHeight) {
      this.titleTable.width(this.titleDiv.width()-15);
      this.dataTable.width(this.titleDiv.width()-15);
      //如果显示滚动条,则需要再次更新第一列宽度
      dataTableTdsFirst.each(function(i){
        if(entity.widths[i])
          $(this).width(entity.widths[i]);
        else//取表头的字段宽度
          $(this).width(titleTableTds.eq(i).width());
      });
    } else {
      this.titleTable.width(this.titleDiv.width());
      this.dataTable.width(this.titleDiv.width());
    }
  },
  updateHeight : function() {
    switch(typeof(this.height)) {
      case 'number' : this.dataDiv.height(this.height-this.titleTable.get(0).offsetHeight);break;
      case 'function' : this.dataDiv.height(this.height());break;
    }
  }
  
};

//checkBox select
BoxSelect = function(config) {

  this.allId = config.allId;
  this.boxName = config.boxName;
  
  this.init();
}

BoxSelect.prototype = {
  init : function(){
    //选择控件实体
    var boxSelectEntity = this;
    //获得全选Box
    this.allBox = $('#'+this.allId);
    //tr集合
    this.trs = [];
    //获得所有namebox
    this.boxes = $('input:checkbox[name="'+this.boxName+'"]');
    var aTable = this.boxes.eq(0).parents('TABLE');
    aTable.addClass('unselect');
    aTable.bind('selectstart', function(){return false;});
    
    //循环
    this.boxes.each(function(){
      var pTr = $(this).parents('TR');
      boxSelectEntity.trs.push(pTr);
      pTr.unbind('click');
      pTr.bind('click', function(event){
        boxSelectEntity.checkLine(this, event);
      });
	  $(this).bind("click",function(){
		   if(!$(this).attr('checked'))
		  {
			 $(this).attr('checked', true);
			 pTr.addClass('selected');
		  }
		 else
		 {
			$(this).removeAttr('checked');
			pTr.removeClass('selected');
		 }
	  });
    });
    
    //绑定全选事件
    this.allBox.unbind('click');
    this.allBox.bind('click', function(){
      boxSelectEntity.checkAll();
    });
  },
  //选择行
  checkLine : function(trObj, e){
    //选择控件实体
    var boxSelectEntity = this;
    //获得event
    var eve = window.event ? window.event : e;
    var srcElement = eve.srcElement || eve.target;
    
    //转换tr
    var jTr = $(trObj);
    //得到tr所属的table
    var jTable = jTr.parents('TABLE');
    //得到box
    var jBox = jTr.find('input:checkbox[name="'+this.boxName+'"]');
    //如果没有按住CTRL并且按的不是checkbox,按的是TD或者SPAN
   // if(!eve.ctrlKey && !eve.shiftKey && (srcElement.tagName=='TD' || srcElement.tagName=='SPAN') && srcElement.type!='checkbox')
//    {
//      if(!jBox.attr('checked'))
//      {
//        jBox.attr('checked', true);
//      
//        取消掉所有的样式
//        jTable.find('tr.selected').each(function(){
//          $(this).removeClass('selected');
//          $(this).find('input:checkbox[name="'+boxSelectEntity.boxName+'"]').removeAttr('checked');
//        });
//      }
//    }
//    //按住了CTRL
//    else if(eve.ctrlKey && (srcElement.tagName=='TD' || srcElement.tagName=='SPAN') && srcElement.type!='checkbox')
//    {
//      //取消或选择
//      if(jBox.attr('checked'))
//        jBox.removeAttr('checked');
//      else
//        jBox.attr('checked', true);
//    }
//    //按住了SHIFT
//    else if(eve.shiftKey)
//    {
//      //获得被选中的box
//      var selecteds = jTable.find('tr.selected');
//      //如果有被选中
//      if(selecteds.length>0)
//      {
//        //获得开始下标
//        var s_index = this.boxes.index(selecteds.eq(0).find('input:checkbox[name="'+this.boxName+'"]'));
//        //获得结束下标
//        var e_index = this.boxes.index(jBox);
//        //如果开始大于结束,互换值
//        if(s_index>e_index)
//        {
//          s_index += e_index;
//          e_index = s_index - e_index;
//          s_index -= e_index;
//        }
//        //取消掉所有的样式
//        jTable.find('tr.selected').each(function(){
//          $(this).removeClass('selected');
//          $(this).find('input:checkbox[name="'+boxSelectEntity.boxName+'"]').removeAttr('checked');
//        });
//        //标记选中
//        for(var i=s_index; i<=e_index; i++)
//        {
//          this.boxes.eq(i).attr('checked', true);
//          this.boxes.eq(i).parents('TR').addClass('selected');
//        }
//      }
//      else
//      {
//        //取消或选择
//        if(jBox.attr('checked'))
//          jBox.removeAttr('checked');
//        else
//          jBox.attr('checked', true);
//      }
//    }
    
    //被选添加样式,没选取消样式
    if(!jBox.attr('checked'))
	{
		jBox.attr('checked', true);
     	jTr.addClass('selected');
	}
    else
    {
		jBox.removeAttr('checked');
		jTr.removeClass('selected');
	}
    
    //如果全部选择了,激活allBox
    if($('input:checkbox[name="'+this.boxName+'"]:checked').length==this.boxes.length)
      this.allBox.attr('checked', true);
    else
      this.allBox.removeAttr('checked');

  },
  //全选或者全部取消
  checkAll : function(){
     if(this.allBox.attr('checked'))
    {
      for(var i=0; i<this.boxes.length; i++)
      {
        this.boxes.eq(i).attr('checked', true);
      }
      for(var i=0; i<this.trs.length; i++)
      {
        this.trs[i].addClass('selected');
      }
    }
    else
    {
      for(var i=0; i<this.boxes.length; i++)
      {
        this.boxes.eq(i).removeAttr('checked');
      }
      for(var i=0; i<this.trs.length; i++)
      {
        this.trs[i].removeClass('selected');
      }
    }
  },
  unCheckAll : function(){
      for(var i=0; i<this.boxes.length; i++)
      {
        this.boxes.eq(i).removeAttr('checked');
      }
      for(var i=0; i<this.trs.length; i++)
      {
        this.trs[i].removeClass('selected');
      }
   }
};

//获得cookie值
function GetCookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=")
		if (c_start != -1)
		{
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";",c_start);
			if (c_end == -1)
			{
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return null;
}
//设置cookie值
function SetCookie(c_name, value, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	var ck = c_name + "=" +escape(value) +";path=/"+ ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
	document.cookie = ck;
}